package com.jplus.mvc.util;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

import com.jplus.core.utill.JUtil;

/**
 * 
 *
 * 
 * @author Yuanqy
 */
public class AESUtil {

	static String MODEL = "AES/CFB/NoPadding";
	// static String key = "1234567890123456"; // aes 密钥key ：must be 16
	// static String data = "1234567890123456";// 待加密数据

	public static void main(String[] args) throws Exception {
		String data = "2234567890123456";// 待加密数据
		String key = "1234567890123456";
		byte[] pwd = encrypt(data.getBytes(), key.getBytes());
		System.out.println("密文长度[" + pwd.length + "]\t" + JUtil.byte2Hex(pwd));
		byte[] res = decrypt(pwd, key.getBytes());
		System.out.println("解密明文[" + res.length + "]\t" + JUtil.byte2Hex(res) + "\n" + new String(res));
	}

	public static byte[] encrypt(byte[] src, byte[] key) {
		try {
			SecretKeySpec skeySpec = new SecretKeySpec(key, "AES");
			Cipher cipher = Cipher.getInstance(MODEL);
			IvParameterSpec iv = new IvParameterSpec(key);
			cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
			return cipher.doFinal(src);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	public static byte[] decrypt(byte[] pwd, byte[] key) {
		try {
			SecretKeySpec skeySpec = new SecretKeySpec(key, "AES");
			Cipher cipher = Cipher.getInstance(MODEL);
			IvParameterSpec iv = new IvParameterSpec(key);
			cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
			return cipher.doFinal(pwd);
		} catch (Exception e) {
			return null;
		}
	}
}